<?php
namespace app\common\lib;
class WxTemplateMessage {
    public static function send($touser, $templateId, $formId, array $query, $emphasisKeyword, $data){
        $token = '';
        try {
            $redis = new Redis();
            $token = $redis->get('wx_access_token');
            $redis->close();
        } catch (\Exception $e) {
        }
        
        if(empty($token)) {
            throw new \Exception('ACCESS_TOKEN');
        }
        
        $ch = curl_init('https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $token);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); //设置超时
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);//严格校验
        
        $params = [
            'touser' => $touser,
            'template_id' => $templateId,
            'form_id' => $formId,
            'data' => [],
            'emphasis_keyword' => $emphasisKeyword
        ];
        
        foreach ($data as $k => $value) {
            $key = 'keyword' . ($k + 1);
            $params['data'][$key] = ['value' => $value];
        }
        
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}